const qiniuUploader = require("../qiniu/qiniuUploader.js");
var siteinfo = require("../siteinfo.js");
//助手函数
var customUtil = {
  /** 获取路由真实路径
   * @ routeName 路由的根目录名称
   * @ param 携带的参数，对象需要做编码解码处理
   */
  getRoute(routName, param = '') {
    if (typeof param === 'object') {
      param = JSON.stringify(param);
      param = encodeURIComponent(param);
    }
    return `../${routName}/${routName}?param=${param}`
  },

  //解码参数, @ param 为 encode编码后的字符串
  decodeParam(param) {
    param = decodeURIComponent(param);
    return JSON.parse(param);
  },

  //数组返回对象数组
  //数组返回对象，对象属性有  $prop, index
  objectArray(arr, prop) {
    if (prop === undefined) {
      throw new Error("The prop is not undefined.Please pass the param 'prop'");
    }
    var res = [];
    arr.forEach((e, index) => {
      let obj = {};
      obj[prop] = e;
      obj.index = index;
      res.push(obj);
    });
    return res;
  },

  //移除数组的元素
  removeArrayEl(arr, index) {
    var copyArr = [];
    arr.forEach((e, idx) => {
      if (index !== idx) {
        copyArr.push(e);
      }
    });
    return copyArr;
  },

  //重新排列数组的 index
  resetArrayIndex(arr) {
    for (let i = 0; i < arr.length; i++) {
      arr[i].index = i;
    }
    return arr;
  },

  //根据时间戳，获取是几天前
  getDayDescription(datetime) {
    var timestamp = new Date(datetime).getTime();
    //昨天还是今天，还是几天前
    var dayDescription = "";
    //获取今天 0 点 时间戳
    var date = new Date();
    date.setHours(0, 0, 0);
    var todayTimestamp = date.getTime();

    //获取  回答的时间戳 - 0点的时间戳 / 一天的时间戳
    var timeDiff = todayTimestamp - timestamp;
    var dayDiff = timeDiff / (1000 * 60 * 60 * 24);
    
    dayDiff = Math.floor(dayDiff);

    if (dayDiff < 0) {
      dayDescription = "今天";
    }
    else if (dayDiff == 0) {
      dayDescription = "昨天";
    }
    else {
      dayDescription = dayDiff + "天前";
    }

    return dayDescription;
  },
  //播放音频，时间给定
  playVoice(innerAudioContext, duration) {
    return new Promise(function (resolve, reject) {
      duration = duration * 1000 + 500;
      let time = 0;
      innerAudioContext.play();
      innerAudioContext.timer = setInterval(() => {
        time += 10;
        if (time >= duration) {
          innerAudioContext.stop();
          clearInterval(innerAudioContext.timer);
          resolve();
        }
      }, 10);

    });

  },

  //验证手机号码正则
  phoneIsRight(str) {
    //验证手机号码正则
    var re = /^1\d{10}$/
    if (re.test(str)) {
      return true;
    } else {
      return false
    }
  },

  //验证身份证号
  idCardIsRight(card) {
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(card);
  },

  //发送 get 请求，返回 promise
  httpGet(url, data) {
    url = siteinfo.siteroot + "/fastAsk/public/index.php/" + url;

    if (data === undefined) {
      data = {};
    }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: data,
        success(res) {
          resolve(res.data);
        },
        fail() {
          reject();
        }
      })
    });
  },
  //发送 post 请求，返回promise
  httpPost(url, data) {
    url = siteinfo.siteroot + "/fastAsk/public/index.php/" + url;
    if (data === undefined) {
      data = {};
    }
    return new Promise(function (resolve, reject) {
      wx.request({
        url: url,
        data: data,
        method: 'POST',
        "Content-Type": "application/x-www-form-urlencoded",
        success(res) {
          resolve(res.data);
        },
        fail() {
          reject();
        }
      })
    });
  },
  //异步控制
  asyncController: {
    note: {},
    addCrowdThen(dutyName, number, callback) {
      this.note[dutyName] = {
        number: number,
        nowNumber: 0,
        callback: callback
      };
    },
    ringCrowdThen(dutyName) {
      this.note[dutyName].nowNumber++;
      if (this.note[dutyName].nowNumber >= this.note[dutyName].number) {
        this.note[dutyName].callback();
      }
    }
  },
  //获取用户信息
  getUserInfo() {
    return new Promise(function (resolve, reject) {
      wx.getUserInfo({
        success(res) {
          resolve(res.userInfo);
        },
        fail(res) {
          reject();
        }
      })
    });
  },
  //获取 datetime格式 日期
  getDateTime() {
    var res = "";
    var date = new Date();
    res = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    return res;
  },
  //上传文件
  upload(filePath, code) {
    var app = getApp();
    var index = filePath.indexOf("tmp");
    var key = code + "/" + filePath.substring(index);
    qiniuUploader.upload(filePath, (res) => {
      // 每个文件上传成功后,处理相关的事情
      // 其中 info 是文件上传成功后，服务端返回的json，形式如
      // {
      //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
      //    "key": "gogopher.jpg"
      //  }
      // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
    }, (error) => {
      console.log('error: ' + error);
    }, {
        key: key,
        region: 'ECN',
        domain: app.appInfo.qiniuInfo.domain, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
        uptokenURL: app.appInfo.qiniuInfo.uptokenURL, // 从指定 url 通过 HTTP GET 获取 uptoken，返回的格式必须是 json 且包含 uptoken 字段，例如： {"uptoken": "[yourTokenString]"}
      }, (res) => {
        console.log('上传进度', res.progress)
        console.log('已经上传的数据长度', res.totalBytesSent)
        console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
      });
  },
  //七牛云上传文件
  qiniuUploadFile(filePath, code) {
    let app = getApp();
    let that = this;



    var files = filePath;
    if (typeof filePath === "string") {
      files = [filePath];
    }
    files.forEach(file => {
      this.upload(file, code);
    });
  },
  dealUploadFilePath(filePath, code) {
    let app = getApp();
    var index = filePath.indexOf("tmp");
    var res = "http://" + app.appInfo.qiniuInfo.domain + "/" + code + "/" + filePath.substring(index);
    return res;
  }


}



module.exports = customUtil;